<?php

namespace app\bews\controller;
use app\bews\model\Base;
use think\app;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\View;

class Login extends Base
{
    public function index(){
//        echo md5(123456);
        return View::fetch();
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function login(){
//        print_r(input('post.account'));
        $account = trim(input('post.account'));
        $password = trim(input('post.password'));
        $code = trim(input('post.code'));
        if(!captcha_check($code)){
            echo json_encode(['code'=>1,'msg'=>'验证码错误']);
            exit();
        }

        $user = Db::table("bew_admin_user")->where('account',$account)->find();

        if($user != null){
            if($user['password'] != $password){
                echo json_encode(['code'=>1,'msg'=>'出错啦,密码错误']);
                exit();
            }else{
                echo json_encode(['code'=>0,'msg'=>'登录成功']);
            }
        }else{
            echo json_encode(['code'=>1,'msg'=>'出错啦,账号不存在']);
            exit();
        }
        Cookie::set("admin_id",$user['uid']);
        Cookie::set("admin_name",$user['name']);

        Db::table("bew_admin_user")->where('uid',$user['uid'])->update([
            'times_login'=>$user['times_login']+1,
        ]);
    }

    public function logout(){
        Cookie::delete("admin_id");
        echo json_encode(['code'=>0,'msg'=>'退出登录成功']);
    }
}